package com.jy.adscm.operation.cg.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jy.adscm.bean.system.JyUser;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.operation.cg.bean.*;
import com.jy.adscm.operation.cg.mapper.mysql.*;
import com.jy.adscm.operation.cg.service.CgTaskService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jy.adscm.operation.cg.utls.NumberToCN;
import com.jy.adscm.operation.mail.bean.MailBean;
import com.jy.adscm.operation.mail.utils.MailUtil;
import com.jy.adscm.operation.mscyb.bean.JqylMaterial;
import com.jy.adscm.operation.mscyb.mapper.mysql.JqylMaterialMapper;
import com.jy.adscm.operation.mscyb.service.JqylMaterialService;
import com.jy.adscm.security.utils.Token;
import com.jy.adscm.system.mapper.mysql.JyUserMapper;
import com.jy.adscm.utils.AdscmBaseUtils;
import com.jy.adscm.utils.AdscmDateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 采购任务 服务实现类
 * </p>
 *
 * @author zyl
 * @since 2019-07-07
 */
@Service
public class CgTaskServiceImpl extends ServiceImpl<CgTaskMapper, CgTask> implements CgTaskService {
   @Autowired
   CgTaskDetailMapper cgTaskDetailMapper;
   @Autowired
   CgSupplierMapper cgSupplierMapper;
   @Autowired
    JyUserMapper jyUserMapper;
   @Autowired
    CgMaterialMapper cgMaterialMapper;
   @Autowired
    MailUtil mailUtil;
   @Autowired
   JqylMaterialMapper jqylMaterialMapper;
   @Autowired
    JqylMaterialService jqylMaterialService;
    @Override
    public boolean updateCgTask(CgTask cgTask, Token token) {
        CgTask oldCgTask = super.selectById(cgTask.getId());
        //判断一下如果老三个都不等
        if (!(oldCgTask.getIsArrive()==1 && oldCgTask.getIsDeliver()==1
                &&oldCgTask.getIsPay()==1&&oldCgTask.getIsReceiveInvoice()==1)){
            if (cgTask.getIsArrive()==1 && cgTask.getIsDeliver()==1
                    &&cgTask.getIsPay()==1&&cgTask.getIsReceiveInvoice()==1){
                cgTask.setState(1);

            }
        }

        //启动任务
          if (cgTask.getIsStart()==1&&cgTask.getState()==0){
              cgTask.setStartTime(new Date());
              cgTask.setCgPerson(token.getUser().getId().toString());
           }
              //结束任务
            if (cgTask.getIsReceiveInvoice()==1&&cgTask.getState()==1){
                cgTask.setTaskFinishTime(new Date());
            }
            //开始备货
            if (cgTask.getIsStockUp()==1){
                if (oldCgTask.getIsStockUp()==0){
                    cgTask.setStockUpTime(new Date());
                }
            }
            //备货检测
        if (cgTask.getIsCheckUp()==1){
            if (oldCgTask.getIsCheckUp()==0){
                cgTask.setCheckUpTime(new Date());
            }
        }
        //发货
        if (cgTask.getIsDeliver()==1){
            if (oldCgTask.getIsDeliver()==0){
                cgTask.setDeliverTime(new Date());
            }
        }
        //到货
        if (cgTask.getIsArrive()==1){
            if (oldCgTask.getIsArrive()==0){
                cgTask.setDeliverTime(new Date());
                cgTask.setKfPerson(token.getUser().getId().toString());
                //生成机器入库单
//                Wrapper<CgTaskDetail> wrapper=new EntityWrapper<>();
//                wrapper.eq("tid",cgTask.getId());
//                List<CgTaskDetail> cgTaskDetails = cgTaskDetailMapper.selectList(wrapper);
//                for (CgTaskDetail cgTaskDetail : cgTaskDetails) {
//                    JqylMaterial jqylMaterial=new JqylMaterial();
//                    jqylMaterial.setTaskreleaseperson(token.getUser().getId().toString());
//                    jqylMaterial.setTaskreleaseaddtime(new Date());
//                    jqylMaterial.setTaskfinishstate(0);
//                    jqylMaterial.setTaskstate(0);
//                    jqylMaterial.setIstaskstart("0");
//                    jqylMaterial.setIstaskbegin("0");
//                    jqylMaterial.setIstaskend("0");
//                    jqylMaterial.setIsreviewtask("0");
//                    jqylMaterial.setReviewresult("-1");
//                    jqylMaterial.setResourcename(cgTaskDetail.getBomName().toString());
//                    jqylMaterial.setTasknums(Double.valueOf(String.valueOf(cgTaskDetail.getNums())));
//                    jqylMaterial.setActualcompletenums(Double.valueOf(String.valueOf(cgTaskDetail.getActNums())));
//                    jqylMaterialMapper.insert(jqylMaterial);
//                }
            }
        }
        //付款
        if (cgTask.getIsPay()==1){
            if (oldCgTask.getIsPay()==0){
                cgTask.setPayAddTime(new Date());
                cgTask.setCwPerson(token.getUser().getId().toString());
            }
        }
        //收票
        if (cgTask.getIsReceiveInvoice()==1){
            if (oldCgTask.getIsReceiveInvoice()==0){
                cgTask.setReceiveInvoiceAddTime(new Date());
                cgTask.setCwPerson(token.getUser().getId().toString());
            }
        }
        boolean b = super.updateById(cgTask);
        return b;
    }

    @Override
    public Page<CgTask> selectCgTask(Page<CgTask> page, QueryCgTask queryCgTask) {
        Wrapper<CgTask> wrapper =new EntityWrapper<>();
        if (AdscmBaseUtils.getInstance().isNotEmpty(queryCgTask.getMakeNo(),null)){
            wrapper.like("make_no",queryCgTask.getMakeNo());
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(queryCgTask.getOrderNums(),null)){
            wrapper.like("order_nums",queryCgTask.getOrderNums());
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(queryCgTask.getSupplier(),null)){
            wrapper.eq("supplier",queryCgTask.getSupplier());
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(queryCgTask.getState(),null)){
            wrapper.eq("state",queryCgTask.getState());
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(queryCgTask.getIsArrive(),null)){
            wrapper.eq("is_arrive",queryCgTask.getIsArrive());
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(queryCgTask.getIsPay(),null)){
            wrapper.eq("is_pay",queryCgTask.getIsPay());
        }
        wrapper.orderBy("create_time",false);
       page = super.selectPage(page,wrapper);
        List<CgTask> cgTasks = page.getRecords();
        for (CgTask cgTask : cgTasks) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(cgTask.getCreator(),null)){
                JyUser jyUser = jyUserMapper.selectById(cgTask.getCreator());
                cgTask.setCreatorName(jyUser.getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(cgTask.getCgPerson(),null)){
                JyUser jyUser = jyUserMapper.selectById(cgTask.getCgPerson());
                cgTask.setCgPersonName(jyUser.getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(cgTask.getKfPerson(),null)){
                JyUser jyUser = jyUserMapper.selectById(cgTask.getKfPerson());
                cgTask.setKfPersonName(jyUser.getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(cgTask.getCwPerson(),null)){
                JyUser jyUser = jyUserMapper.selectById(cgTask.getCwPerson());
                cgTask.setCwPersonName(jyUser.getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(cgTask.getSupplier(),null)){
                CgSupplier cgSupplier = cgSupplierMapper.selectById(cgTask.getSupplier());
                cgTask.setSupplierName(cgSupplier);
            }
            //查询这个下面有多少条采购
            Wrapper<CgTaskDetail> cgTaskDetailWrapper=new EntityWrapper<>();
            cgTaskDetailWrapper.eq("tid",cgTask.getId());
            cgTaskDetailWrapper.eq("is_buy",0);
            List<CgTaskDetail> cgTaskDetails = cgTaskDetailMapper.selectList(cgTaskDetailWrapper);
            Date date=null;
            CgTaskDetail temp=new CgTaskDetail();
            Float tempTotals=0f;
            for (CgTaskDetail cgTaskDetail : cgTaskDetails) {
                if (AdscmBaseUtils.getInstance().isNotEmpty(cgTaskDetail.getPlanOrderTime(),null)){
                    if (AdscmBaseUtils.getInstance().isNotEmpty(date,null)){
                        if (date.getTime()>cgTaskDetail.getPlanArriveTime().getTime()){
                            date=cgTaskDetail.getPlanArriveTime();
                            temp=cgTaskDetail;
                        }
                    }else {
                        date= cgTaskDetail.getPlanArriveTime();
                        temp=cgTaskDetail;
                    }
                }
                if (AdscmBaseUtils.getInstance().isNotEmpty(cgTaskDetail.getTotal(),null)){
                    tempTotals=tempTotals+cgTaskDetail.getTotal();
                }

            }
            cgTask.setTotals(tempTotals);
            if (AdscmBaseUtils.getInstance().isNotEmpty(temp,null)){
                CgMaterial cgMaterial = cgMaterialMapper.selectById(temp.getBomName());
                if (AdscmBaseUtils.getInstance().isNotEmpty(cgMaterial,null)){
                    cgTask.setCgTaskDetail(cgMaterial.getName());
                }
                cgTask.setLateOrderTime(date);
            }

        }
        page.setTotal(selectCount(wrapper));
        return page;
    }

    @Override
    public CgOrder selectCgOrderBy(Integer id) throws AdscmSystemException {
        CgTask cgTask = super.selectById(id);
        //查询供应商
        CgSupplier cgSupplier = cgSupplierMapper.selectById(cgTask.getSupplier());
        //查询供方人员
        JyUser jyUser = jyUserMapper.selectById(cgTask.getCgPerson());
        //查询够买详情
        Wrapper<CgTaskDetail> wrapper =new EntityWrapper<>();
        wrapper.eq("tid",cgTask.getId());
        List<CgTaskDetail> cgTaskDetails = cgTaskDetailMapper.selectList(wrapper);
        for (CgTaskDetail cgTaskDetail : cgTaskDetails) {
            CgMaterial cgMaterial = cgMaterialMapper.selectById(cgTaskDetail.getBomName());
            cgTaskDetail.setBomNameName(cgMaterial.getName());
        }
        CgOrder  cgOrder =new CgOrder();
        cgOrder.setCgSupplier(cgSupplier);
        cgOrder.setJyUser(jyUser);
        cgOrder.setCgTaskDetails(cgTaskDetails);
        return cgOrder;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void sendEmail(MailBean mailBean) throws AdscmSystemException{
        //根据mailBean 里面的contentId 查询到发送的这个任务
        CgTask cgTask = super.selectById(mailBean.getContentId());
        if (!AdscmBaseUtils.getInstance().isNotEmpty(cgTask,null)){
            throw  new AdscmSystemException("未查询到该任务");
        }
        CgSupplier cgSupplier = cgSupplierMapper.selectById(cgTask.getSupplier());
        if (!AdscmBaseUtils.getInstance().isNotEmpty(cgSupplier.getEmail(),null)){
            throw  new AdscmSystemException("该供应商还录入邮箱");
        }
        JyUser jyUser = jyUserMapper.selectById(cgTask.getCgPerson());
        Wrapper<CgTaskDetail> wrapper =new EntityWrapper<>();
        wrapper.eq("tid",cgTask.getId());
        List<CgTaskDetail> cgTaskDetails = cgTaskDetailMapper.selectList(wrapper);
        for (CgTaskDetail cgTaskDetail : cgTaskDetails) {
            CgMaterial cgMaterial = cgMaterialMapper.selectById(cgTaskDetail.getBomName());
            cgTaskDetail.setBomNameName(cgMaterial.getName());
        }
        String cgTaskDetailstr="";
        for (CgTaskDetail cgTaskDetail : cgTaskDetails) {
            cgTaskDetailstr=cgTaskDetailstr+
                    "        <tr>\n" +
                    "           <td>"+cgTaskDetail.getBomNameName()+"</td>\n" +
                    "            <td>"+cgTaskDetail.getType()+"</td>\n" +
                    "            <td>"+cgTaskDetail.getPrice()+"</td>\n" +
                    "            <td>"+cgTaskDetail.getNums()+"</td>\n" +
                    "            <td>"+cgTaskDetail.getTotal()+"</td>\n" +
                    "            <td>"+ AdscmDateUtils.getNowOnlyDateFomat1(cgTaskDetail.getPlanArriveTime())+"</td>\n" +
                    "            <td>"+cgTaskDetail.getRemark()+"</td>\n" +
                    "        </tr>\n" ;
        }


        mailBean.setSubject("成都佳颖 订货通知单");
        String text="<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>Title</title>\n" +
                "    <style>\n" +
                "        *{\n" +
                "            padding:0;\n" +
                "            margin:0;\n" +
                "        }\n" +
                "        table{\n" +
                "            margin:auto;\n" +
                "            line-height:2;\n" +
                "        }\n" +
                "        .tableList th, .tableList td{\n" +
                "            padding:10px 20px;\n" +
                "        }\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body>\n" +
                "<div>\n" +
                "    <h2 style=\"text-align:center\">成都市佳颖医用制品有限公司</h2>\n" +
                "    <h1 style=\"text-align:center\">订货通知单</h1>\n" +
                "    <table  align=\"center\" style=\"font-size: 16px\">\n" +
                "        <tr>\n" +
                "            <td>供方：</td>\n" +
                "            <td>"+cgSupplier.getName()+"</td>\n" +
                "            <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>\n" +
                "            <td>需方：</td>\n" +
                "            <td>成都市佳颖医用制品有限公司</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td>联系人：</td>\n" +
                "            <td>"+cgSupplier.getContacts()+"</td>\n" +
                "            <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>\n" +
                "            <td>联系人：</td>\n" +
                "            <td>"+jyUser.getName()+"</td>\n" +
                "\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td>联系电话：</td>\n" +
                "            <td>"+cgSupplier.getPhone()+"</td>\n" +
                "            <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>\n" +
                "            <td>联系电话：</td>\n" +
                "            <td>"+jyUser.getPhone()+"</td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td>传真：</td>\n" +
                "            <td>"+cgSupplier.getFax()+"</td>\n" +
                "            <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>\n" +
                "            <td>传真：</td>\n" +
                "            <td>028-8481 4555</td>\n" +
                "        </tr>\n" +
                "    </table>\n" +
                "    <table    align=\"center\" style=\"font-size: 16px\" cellpadding=\"25\"  class=\"tableList\">\n" +
                "        <th>货物名称</th>\n" +
                "\n" +
                "        <th>规格</th>\n" +
                "\n" +
                "        <th>单价(元)</th>\n" +
                "\n" +
                "        <th>数量</th>\n" +
                "\n" +
                "        <th>金额(元)</th>\n" +
                "\n" +
                "        <th>到货时间</th>\n" +
                "\n" +
                "        <th>备注说明</th>\n" +
                cgTaskDetailstr
              +
                "    </table>\n" +
                "    <div class=\"discrtion\"  style=\"width: 712px;margin: auto\">\n" +
                "        <div class=\"discrtion-title\">说明事项：</div>\n" +
                "        <div>1、供方提供的每批货物必须有相关的检测报告和生产批号，且生产批号尽可能的少。检测报告请随货一同发出。</div>\n" +
                "        <div>2、质量要求按双方确认执行。</div>\n" +
                "        <div>3、以上时间为到货时间，请供方提前发货。</div>\n" +
                "        <div>4、请供方开增值税专用发票。</div>\n" +
                "        <div>5、供方在设备、材料、模具等方面发生更改时，请提前通知需方。</div>\n" +
                "        <div>5、以上内容供方如无异议，请签章确认或电话回复。</div>\n" +
                "    </div>\n" +
                "</div>\n" +
                "\n" +
                "</body>\n" +
                "</html>";


        mailBean.setReceiver(cgSupplier.getEmail());
        mailBean.setText(text);
        mailUtil.sendMailHtml(mailBean);
        cgTask.setIsSendEmail(1);
        super.updateById(cgTask);
    }

    @Override
    public Boolean startCgTask(Integer id) throws AdscmSystemException {
        CgTask cgTask = super.selectById(id);
        if (AdscmBaseUtils.getInstance().isNotEmpty(cgTask,null)){
            if (cgTask.getIsStart()==0){
                cgTask.setIsStart(1);
                super.updateById(cgTask);
            }

        }else {
          throw  new AdscmSystemException("未查到该信息");
        }
        return null;
    }

    @Override
    public CgPayOrder selectCgPayOrderBy(Integer id) {

        DecimalFormat df=new DecimalFormat("#.00");
        CgTask cgTask = super.selectById(id);
        //查询供应商
        CgSupplier cgSupplier = cgSupplierMapper.selectById(cgTask.getSupplier());
        //查询供方人员
        JyUser jyUser = jyUserMapper.selectById(cgTask.getCgPerson());
        //查询够买详情
        Wrapper<CgTaskDetail> wrapper =new EntityWrapper<>();
        wrapper.eq("tid",cgTask.getId());
        List<CgTaskDetail> cgTaskDetails = cgTaskDetailMapper.selectList(wrapper);
        double total=0;
        Date date=null;
        for (CgTaskDetail cgTaskDetail : cgTaskDetails) {
            CgMaterial cgMaterial = cgMaterialMapper.selectById(cgTaskDetail.getBomName());
            cgTaskDetail.setBomNameName(cgMaterial.getName());
            if (AdscmBaseUtils.getInstance().isNotEmpty(cgTaskDetail.getNums(),null)){
                if (AdscmBaseUtils.getInstance().isNotEmpty(cgTaskDetail.getPrice(),null)){
                    total=+total+  cgTaskDetail.getNums()*cgTaskDetail.getPrice();
                }
            }

            if (AdscmBaseUtils.getInstance().isNotEmpty(cgTaskDetail.getPlanPayTime(),null)){
                if (AdscmBaseUtils.getInstance().isNotEmpty(date,null)){
                  if (date.getTime()<cgTaskDetail.getPlanPayTime().getTime()){
                      date=cgTaskDetail.getPlanPayTime();
                  }
                }else {
                    date=cgTaskDetail.getPlanPayTime();
                }
            }
        }

        CgPayOrder cgPayOrder =new CgPayOrder();
        cgPayOrder.setJyUser(jyUser);
        cgPayOrder.setCgSupplier(cgSupplier);
        cgPayOrder.setCgTaskDetails(cgTaskDetails);
        cgPayOrder.setTotal(Double.valueOf(df.format(total)) );
        BigDecimal numberOfMoney = new BigDecimal(total);
        String s = NumberToCN.number2CNMontrayUnit(numberOfMoney);
        cgPayOrder.setAtotal(s);
        cgPayOrder.setLatePayDate(AdscmDateUtils.getNowOnlyDateFomat1(date));
        return cgPayOrder;
    }

    @Override
    public Float selectTotals(QueryCgTask queryCgTask) {
        Wrapper<CgTask> wrapper =new EntityWrapper<>();
        if (AdscmBaseUtils.getInstance().isNotEmpty(queryCgTask.getMakeNo(),null)){
            wrapper.like("make_no",queryCgTask.getMakeNo());
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(queryCgTask.getOrderNums(),null)){
            wrapper.like("order_nums",queryCgTask.getOrderNums());
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(queryCgTask.getSupplier(),null)){
            wrapper.eq("supplier",queryCgTask.getSupplier());
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(queryCgTask.getState(),null)){
            wrapper.eq("state",queryCgTask.getState());
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(queryCgTask.getIsArrive(),null)){
            wrapper.eq("is_arrive",queryCgTask.getIsArrive());
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(queryCgTask.getIsPay(),null)){
            wrapper.eq("is_pay",queryCgTask.getIsPay());
        }
        List<CgTask> cgTasks = super.selectList(wrapper);
        Float cgTaskTotals=0f;
        for (CgTask cgTask : cgTasks) {
            Wrapper<CgTaskDetail> cgTaskDetailWrapper=new EntityWrapper<>();
            cgTaskDetailWrapper.eq("tid",cgTask.getId());
            List<CgTaskDetail> cgTaskDetails = cgTaskDetailMapper.selectList(cgTaskDetailWrapper);
            Float cgTaskDetailTotals=0f;
            for (CgTaskDetail cgTaskDetail : cgTaskDetails) {
                if (AdscmBaseUtils.getInstance().isNotEmpty(cgTaskDetail.getTotal(),null)){
                    cgTaskDetailTotals=cgTaskDetailTotals+cgTaskDetail.getTotal();
                }
            }
            cgTaskTotals=cgTaskTotals+cgTaskDetailTotals;
        }

        return cgTaskTotals;
    }
}
